#!/usr/bin/env bash
set -ex

[ -n "$AWS_ACCESS_KEY_ID" ] || {
  echo "AWS_ACCESS_KEY_ID is not set"
  exit 0
}

[ -n "$AWS_SECRET_ACCESS_KEY" ] || {
  echo "AWS_SECRET_ACCESS_KEY is not set"
  exit 0
}

cd $(dirname $0)/..

source ./scripts/version.sh

RPM_LIST=$(mktemp -t)
TMPDIR=$(mktemp -d)
cleanup() {
  exit_code=$?
  trap - EXIT INT
  rm -rf "${TMPDIR}" "${RPM_LIST}"
  exit ${exit_code}
}
trap cleanup EXIT INT

RPM_DIR='./dist/rpms'

find "${RPM_DIR}" -mindepth 2 -type f \( -name '*.rpm' -not -name '*.src.rpm' \) -print >"${RPM_LIST}"
while IFS= read -r FILE; do
  KIND=$(echo "${FILE}" | grep -oE 'rke2-\w+')
  DISTRO=$(basename "${FILE%%x86_64*}")
  cp "${FILE}" "${RPM_DIR}/${KIND}-${COMMIT}.${DISTRO}.rpm"
done <"${RPM_LIST}"

umask 077

aws s3 cp ${RPM_DIR}/ s3://rke2-ci-builds --exclude "*" --include "*.rpm" --recursive || exit 1

echo "Build uploaded" >&2
echo "https://rke2-ci-builds.s3.amazonaws.com/${BUNDLE_NAME}"
